package com.ldodds.deville.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import com.hp.hpl.jena.util.FileManager;

/**
 * This class provides some different options for finding the 
 * OpenCalais licence key in the users environment.
 * 
 * @author Leigh Dodds
 */
public class LicenceKeys
{
	/**
	 * Read the licence key from a file called <code>calais-key.txt</code> 
	 * in the users home directory.
	 * 
	 * @return the key, or null if the file doesn't exist
	 */
	public static String getKeyFromUserHome() {
		String key = null;
		String userHome = System.getProperty("user.home");
		File keyFile = new File(userHome, "calais-key.txt");
		try {
			key = FileManager.get().readWholeFileAsUTF8(
				new FileInputStream(keyFile) );
		} catch (IOException e) {		
			//TODO logging
			e.printStackTrace();
		}
		return key;
	}
	
	/**
	 * Read the OpenCalais licence key from a system property 
	 * called <code>calais-key</code>. This allows the key 
	 * to be set from the command-line using:
	 * 
	 * <code>
	 * java -Dcalais-key=XYZ ...
	 * </code>
	 * @return the key or null if there's no property of that name
	 */
	public static final String getKeyFromSystemProperty() {
		return System.getProperty("calais-key");
	}

	/**
	 * Read the OpenCalais licence key from an environment 
	 * property called <code>CALAIS-KEY</code>. This allows the 
	 * key to be set externally to the JVM.
	 * 
	 * @return the key or null if there's no environment variable of that name
	 */
	public static final String getKeyFromEnvironment() {
		return System.getenv("CALAIS-KEY");
	}
	
	/**
	 * Makes a best effort attempt to discover the OpenCalais licence 
	 * key. It tries, in order:
	 * <ol>
	 * <li>A system property, <code>calais-key</code></li>
	 * <li>An environment variable, <code>CALAIS-KEY</code></li>
	 * <li>Reading a file called <code>calais-key.txt</code> in the users 
	 * home directory</li>
	 * </ol> 
	 * 
	 * @return the key, or null if it can't be found by any method
	 */
	public static String getKey() {
		String key = getKeyFromSystemProperty();
		if (key == null) {
			key = getKeyFromEnvironment(); 
		}
		if (key == null) {
			key = getKeyFromUserHome(); 
		}
		
		return key;
	}
}
